#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstring>
#include <arpa/inet.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include "ThreadPool.hpp"
#include <functional>

using namespace std;


class TcpServer
{
    void Service(int fd, struct sockaddr_in peer)//这里不能用引用类型，会有问题
    {
        char buffer[80];
        while(1)
        {
            int n= read(fd, buffer, sizeof(buffer)-1);
            if(n> 0)
            {
                buffer[n]= 0;
                cout<<"client say# "<<buffer<<endl;

                string ret= "server echo# ";
                ret+= buffer;
                write(fd, ret.c_str(), ret.size());
            }
            else if(n== 0)
            {
                cout<<"连接断开，客户端为："<<inet_ntoa(peer.sin_addr)<<" "<<ntohs(peer.sin_port)<<endl;
                break;
            }
        }

        //将与客户端的通信作为一个任务，加入线程池中交给线程处理，那这个任务就必须把善后也做了
        close(fd);
    }

    void ConnectionHandle(int fd, struct sockaddr_in& peer)
    {
        function<void()> task= bind(&TcpServer::Service, this, fd, peer);
        ThreadPool::GetInstance()->Enqueue(task);
    }
public:
    TcpServer(int port)
    :_port(port)
    {}

    void Init()
    {
        _sockfd= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family= AF_INET;
        local.sin_addr.s_addr= htonl(INADDR_ANY);
        local.sin_port= htons(_port);

        int opt=1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        bind(_sockfd, (struct sockaddr*)&local, sizeof(local));

        listen(_sockfd, 8);
    }

   

    void Start()
    {
        _isrunning= true;

        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len= sizeof(peer);
            int fd= accept(_sockfd, (struct sockaddr*)&peer, &len);

            cout<<"client connected: "<<inet_ntoa(peer.sin_addr)<<" "<<ntohs(peer.sin_port)<<endl;
            ConnectionHandle(fd, peer);
        }
    }

private:
    int _port;
    int _sockfd;
    bool _isrunning;
};


int main()
{
    ThreadPool::GetInstance()->Start();
    TcpServer server(65535);
    server.Init();
    server.Start();

    

    return 0;
}